// 短语API客户端模块
const PhrasesApiClient = (() => {
  const BASE_URL = window.location.origin;
  
  /**
   * 通用API请求方法
   * @param {string} url - 请求的URL路径
   * @param {Object} options - 请求选项配置
   * @returns {Promise<Object>} 返回解析后的JSON响应数据
   */
  const request = async (url, options = {}) => {
    try {
      const response = await fetch(`${BASE_URL}${url}`, {
        headers: {
          'Content-Type': 'application/json',
          ...options.headers
        },
        ...options
      });
      
      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || `HTTP ${response.status}`);
      }
      
      return await response.json();
    } catch (error) {
      throw error;
    }
  };
  
  /**
   * 获取用户个人短语库
   * @returns {Promise<Array>} 返回短语数组
   */
  const getAllPhrases = async () => {
    const user = getCurrentUser();
    if (!user || !user.id) {
      throw new Error('用户未登录或用户信息无效');
    }
    
    const response = await request(`/api/phrases?userId=${user.id}`);
    return response.phrases || [];
  };
  
  /**
   * 获取当前用户信息
   * @returns {Object|null} 返回用户信息或null
   */
  const getCurrentUser = () => {
    try {
      let userStr = localStorage.getItem('user');
      if (!userStr) {
        userStr = sessionStorage.getItem('user');
      }
      return userStr ? JSON.parse(userStr) : null;
    } catch (error) {
      return null;
    }
  };
  
  /**
   * 添加新短语到用户个人短语库
   * @param {Object} phraseData - 短语数据对象
   * @param {string} phraseData.phrase - 短语
   * @param {string} phraseData.translation - 翻译
   * @param {string} phraseData.example - 例句
   * @returns {Promise<Object>} 返回添加的短语对象
   */
  const addPhrase = async (phraseData) => {
    const user = getCurrentUser();
    if (!user || !user.id) {
      throw new Error('用户未登录或用户信息无效');
    }
    
    return await request('/api/phrases', {
      method: 'POST',
      body: JSON.stringify({
        ...phraseData,
        userId: user.id
      })
    });
  };
  
  /**
   * 更新用户个人短语库中的短语
   * @param {string} id - 短语ID
   * @param {Object} phraseData - 更新的短语数据
   * @returns {Promise<Object>} 返回更新后的短语对象
   */
  const updatePhrase = async (id, phraseData) => {
    const user = getCurrentUser();
    if (!user || !user.id) {
      throw new Error('用户未登录或用户信息无效');
    }
    
    return await request(`/api/phrases/${id}`, {
      method: 'PUT',
      body: JSON.stringify({
        ...phraseData,
        userId: user.id
      })
    });
  };
  
  /**
   * 从用户个人短语库中删除短语
   * @param {string} id - 短语ID
   * @returns {Promise<Object>} 返回删除结果
   */
  const deletePhrase = async (id) => {
    const user = getCurrentUser();
    if (!user || !user.id) {
      throw new Error('用户未登录或用户信息无效');
    }
    
    return await request(`/api/phrases/${id}?userId=${user.id}`, {
      method: 'DELETE'
    });
  };
  
  /**
   * 切换用户个人短语库中短语的记忆状态
   * @param {string} id - 短语ID
   * @returns {Promise<Object>} 返回更新后的短语对象
   */
  const toggleMemorized = async (id) => {
    const user = getCurrentUser();
    if (!user || !user.id) {
      throw new Error('用户未登录或用户信息无效');
    }
    
    return await request(`/api/phrases/${id}/memorized`, {
      method: 'PATCH',
      body: JSON.stringify({
        userId: user.id
      })
    });
  };
  
  /**
   * 搜索短语
   * @param {string} query - 搜索关键词
   * @returns {Promise<Array>} 返回匹配的短语数组
   */
  const searchPhrases = async (query) => {
    const user = getCurrentUser();
    if (!user || !user.id) {
      throw new Error('用户未登录或用户信息无效');
    }
    
    const params = new URLSearchParams({
      userId: user.id,
      q: query || ''
    });
    
    return await request(`/api/phrases/search?${params}`);
  };
  
  return {
    getAllPhrases,
    addPhrase,
    updatePhrase,
    deletePhrase,
    toggleMemorized,
    searchPhrases
  };
})();

// 兼容原有的PhraseData接口
const PhraseData = (() => {
  let phrasesCache = null;
  let isDataLoaded = false;
  
  /**
   * 初始化数据
   * @returns {Promise<Array>} 返回短语数据数组
   */
  const initializeData = async () => {
    if (isDataLoaded && phrasesCache) return phrasesCache;
    
    const user = getCurrentUser();
    if (!user || !user.id) {
      phrasesCache = [];
      isDataLoaded = true;
      return phrasesCache;
    }
    
    try {
      phrasesCache = await PhrasesApiClient.getAllPhrases();
      isDataLoaded = true;
      return phrasesCache;
    } catch (error) {
      phrasesCache = [];
      isDataLoaded = true;
      return phrasesCache;
    }
  };
  
  /**
   * 获取当前用户信息
   * @returns {Object|null} 返回用户信息或null
   */
  const getCurrentUser = () => {
    try {
      let userStr = localStorage.getItem('user');
      if (!userStr) {
        userStr = sessionStorage.getItem('user');
      }
      return userStr ? JSON.parse(userStr) : null;
    } catch (error) {
      return null;
    }
  };
  
  /**
   * 获取所有短语（同步版本）
   * @returns {Array} 返回缓存中的短语数组
   */
  const getAllPhrases = () => {
    return phrasesCache || [];
  };
  
  /**
   * 刷新缓存数据
   * @returns {Promise<Array>} 返回刷新后的短语数组
   */
  const refreshCache = async () => {
    const user = getCurrentUser();
    if (!user || !user.id) {
      phrasesCache = [];
      return phrasesCache;
    }
    
    try {
      phrasesCache = await PhrasesApiClient.getAllPhrases();
      return phrasesCache;
    } catch (error) {
      return phrasesCache || [];
    }
  };
  
  /**
   * 添加新短语
   * @param {Object} phraseData - 短语数据对象
   * @returns {Promise<Object>} 返回新创建的短语对象
   */
  const addPhrase = async (phraseData) => {
    try {
      const newPhrase = await PhrasesApiClient.addPhrase(phraseData);
      if (phrasesCache) {
        phrasesCache.unshift(newPhrase);
      }
      return newPhrase;
    } catch (error) {
      throw error;
    }
  };
  
  /**
   * 更新短语
   * @param {string} id - 短语ID
   * @param {Object} phraseData - 更新的短语数据对象
   * @returns {Promise<Object>} 返回更新后的短语对象
   */
  const updatePhrase = async (id, phraseData) => {
    try {
      const updatedPhrase = await PhrasesApiClient.updatePhrase(id, phraseData);
      if (phrasesCache) {
        const index = phrasesCache.findIndex(phrase => phrase.id === id);
        if (index !== -1) {
          phrasesCache[index] = updatedPhrase;
        }
      }
      return updatedPhrase;
    } catch (error) {
      throw error;
    }
  };
  
  /**
   * 删除短语
   * @param {string} id - 要删除的短语ID
   * @returns {Promise<boolean>} 返回删除操作是否成功
   */
  const deletePhrase = async (id) => {
    try {
      await PhrasesApiClient.deletePhrase(id);
      if (phrasesCache) {
        const index = phrasesCache.findIndex(phrase => phrase.id === id);
        if (index !== -1) {
          phrasesCache.splice(index, 1);
        }
      }
      return true;
    } catch (error) {
      throw error;
    }
  };
  
  /**
   * 切换短语记忆状态
   * @param {string} id - 短语ID
   * @returns {Promise<Object>} 返回更新后的短语对象
   */
  const toggleMemorized = async (id) => {
    try {
      const updatedPhrase = await PhrasesApiClient.toggleMemorized(id);
      if (phrasesCache) {
        const index = phrasesCache.findIndex(phrase => phrase.id === id);
        if (index !== -1) {
          phrasesCache[index] = updatedPhrase;
        }
      }
      return updatedPhrase;
    } catch (error) {
      throw error;
    }
  };
  
  /**
   * 搜索短语
   * @param {string} query - 搜索关键词
   * @returns {Promise<Array>} 返回匹配的短语数组
   */
  const searchPhrases = async (query) => {
    try {
      return await PhrasesApiClient.searchPhrases(query);
    } catch (error) {
      if (!query || !query.trim()) {
        return getAllPhrases();
      }
      
      const phrases = getAllPhrases();
      const lowerQuery = query.trim().toLowerCase();
      return phrases.filter(phrase => 
        phrase.phrase.toLowerCase().includes(lowerQuery) || 
        phrase.translation.toLowerCase().includes(lowerQuery)
      );
    }
  };
  
  return {
    getAllPhrases,
    initializeData,
    refreshCache,
    addPhrase,
    updatePhrase,
    deletePhrase,
    toggleMemorized,
    searchPhrases
  };
})();
